package HouseRent.service;

import HouseRent.domain.House;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:lenovo
 * Date:2024-06-09
 * Time:17:43
 */
public class HouseService {
    private House[] houses;
    private int houseNums=1;
    private int idCounter=1;


    public HouseService(int size) {
        houses=new House[size];
        houses[0]=new House(1,"张三","182","临渭区",3500,"未出租");
        //测试一个
    }
    public boolean add(House newHouse){
        //判断是否还能添加进去，如果不能，需要进行数组扩容
        if(houseNums>= houses.length){
            //数组不够，需要扩容
            houses=arrayExpand(houses);
        }
        houses[houseNums++]=newHouse;
        //我们需要提供一个id自增长机制,使得id自动增长
        newHouse.setId(++idCounter);
        return true;
    }
    public boolean del(int delId){
        int index=-1;
        for (int i = 0; i < houseNums; i++) {
            if(delId==houses[i].getId()){
                index=i;//把id对应房屋的下标记录下来
                break;
            }
        }
        if(index==-1){
            System.out.println("对应id的房间不存在!");
            return false;
        }
        for(int i=index;i<houseNums-1;i++){
            houses[i]=houses[i+1];
        }
        houses[--houseNums]=null;
        //等价于
       /* houses[houseNums-1]=null;
        houseNums--;*/
        return true;
    }
    public House[] list(){
        return houses;
    }
    public House[] arrayExpand(House[] arr){
        House[] brr=new House[arr.length*2];
        for (int i = 0; i < arr.length; i++) {
            brr[i]=arr[i];
        }
        return brr;
    }
    public House findById(int findId){
        for (int i = 0; i < houseNums; i++) {
            if(findId==houses[i].getId()){
                return houses[i];
            }
        }
        return null;
    }
}
